<script setup lang="ts">
import { ref, nextTick, onMounted } from 'vue'
import Sortable from 'sortablejs'

interface Props {
  data?: any[] | never | null
  type?: string
}

const props = withDefaults(defineProps<Props>(), {
  data: null,
  type: 'web'
})

const list = ref<any[]>([])

const dragTableRef = ref()

// 拖拽table排序
const initDropTable = () => {
  const el = dragTableRef.value.$el.querySelector('.el-table__body tbody')
  Sortable.create(el, {
    handle: '.move-el', //设置指定列作为拖拽
    onEnd(evt: any) {
      const { newIndex, oldIndex } = evt
      let copyEl = JSON.parse(JSON.stringify(list.value[oldIndex]))
      list.value.splice(oldIndex, 1)
      list.value.splice(newIndex, 0, copyEl)
      list.value = list.value.map((v: any, i: number) => {
        return {
          id: v.id,
          name: v.name,
          sort: i
        }
      })
      // console.log(list.value)
    }
  })
}

const initList = () => {
  list.value = props.data || []
  nextTick(() => {
    initDropTable()
  })
}

const getSortResult = () => {
  const key = props.type === 'web' ? 'sort' : 'miniSort'
  return list.value.map((item: any, index: number) => {
    return {
      menuId: item.id,
      [key]: list.value.length - 1 - index
    }
  })
}

defineExpose({
  getSortResult
})

onMounted(() => {
  initList()
})
</script>

<template>
  <el-table
    ref="dragTableRef"
    :data="list"
    style="width: 50vw"
    height="50vh"
    class="custom-table"
    row-key="id"
    border
    default-expand-all
    row-class-name="move-el"
  >
    <el-table-column prop="name" align="left" label="菜单名称">
      <template #default="scope">
        <div class="move-el-cursor">{{ scope.row.name }}</div>
      </template>
    </el-table-column>
    <el-table-column prop="id" align="center" label="编号" />
  </el-table>
</template>

<style lang="scss" scoped>
.move-el-cursor {
  cursor: pointer;
}
</style>
